import {Command} from '../constant';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import api from 'api';
import {extraPathsValue} from '@/redux/util';
import Taro from '@tarojs/taro';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },

    /**
     * 查询我的许愿池列表
     * @param payload
     */
    async loadWishItemsByPage(payload) {
      // action.commonChange('main.wishItems', []);
      action.commonChange('main.response.loadWish', '');
      action.commonChange('main.status.loadingWish', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, message, code} = await api.WishBaseController.getUserWishItemsPage(params);
      console.log('action.ts loadWishItemsByPage data', data);

      let result = data.content;

      // 编辑分页参数
      let page = {
        ...payload,
        total: data.total || 0,
      };

      let {
        main: {wishItems},
      } = getData();
      console.log('page.pageNum', page.pageNum);
      if (page.pageNum > 0) {
        result = wishItems.concat(data.content);
      }
      action.commonChange('main.wishItems', result);
      action.commonChange('main.page', page);
      action.commonChange('main.response.loadWish', code);
      action.commonChange('main.status.loadingWish', false);
    },

    /**
     * 查询推荐商品
     */
    async fetchrecommendation() {
      action.commonChange('main.productList', []);
      action.commonChange('main.productListPageNum', 0);

      let {
        main: {productListPageNum, productList},
      } = getData();
      productListPageNum = productListPageNum + 1;

      let {content} = await api.wechatLoginController.recommendmodule({
        pageNum: 0,
        pageSize: 1000,
        moduleType: 1, // 许愿池模块
      });
      content = content || [];
      productList = [...productList, ...content];
      action.commonChange('main.productListPageNum', productListPageNum);
      action.commonChange('main.productList', productList);
    },

    /**
     * 删除失效的许愿
     */
    async removeWish(payload) {
      action.commonChange('main.response.removeWish', '');
      action.commonChange('main.status.removeingWish', true);

      // 编辑参数
      let params = {
        ...payload,
      };

      let {data, message, code} = await api.WishBaseController.removeWishItems(params);
      action.commonChange('main.codeMessage', message);
      action.commonChange('main.response.removeWish', code);
      action.commonChange('main.status.removeingWish', false);
    },
  };
  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageIWishingPoolMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
